import "@/lib/audio.js";
import "@/lib/socket.io.js";

import { SingletonFactory } from "./single";
import { socketSpeekLogin } from "@/api/socket";

declare global {
  interface Window {
    /** SpeechSDK */
    SpeechSDK: Record<string, any>;
    /** io */
    io: Record<string, any>;
  }
}

type Event = "start" | "radio";

export default class Speech extends SingletonFactory<Speech>() {
  creating = false;
  data = null;
  private $on = new Map<Event, Array<Function>>();
  private authorizationToken: any;
  public socket: any = null;
  private recognizer: any;
  private async getToken() {
    const [err, res] = await socketSpeekLogin();
    if (!err) {
      this.authorizationToken = res;
    }
  }
  init() {
    this.getToken();
  }

  on(event: Event, callback: Function) {
    if (this.$on.has(event)) {
      const callbacks = this.$on.get(event) as Array<Function>;
      callbacks.push(callback);
      this.$on.set(event, callbacks);
    } else {
      this.$on.set(event, [callback]);
    }
  }
  off(event: Event) {
    if (this.$on.has(event)) {
      this.$on.delete(event);
    }
  }
  emit(event: Event, value?: any) {
    const eventQueue = this.$on.get(event);
    if (eventQueue?.length) {
      for (let i = 0; i < eventQueue.length; i++) {
        eventQueue[i](value);
      }
    }
  }
  start() {
    this.emit("start");

    // 使用默认的麦克风输入
    const audioConfig =
      window.SpeechSDK.AudioConfig.fromDefaultMicrophoneInput();
    // 创建语音配置
    const speechConfig = window.SpeechSDK.SpeechConfig.fromAuthorizationToken(
      this.authorizationToken,
      "eastus"
    );
    speechConfig.speechRecognitionLanguage = "zh-CN";
    // 创建语音识别器
    this.recognizer = new window.SpeechSDK.SpeechRecognizer(
      speechConfig,
      audioConfig
    );
    console.log("调起了麦克风", this.recognizer);
    // 开始识别
    this.recognizer.recognizeOnceAsync(
      async (result: any) => {
        const recognizedText = result.text;
        console.log("返回语音解析", recognizedText);
        this.emit("radio", recognizedText);
        this.stop();
      },
      (error: any) => {
        console.log(error);
        this.stop();
      }
    );
  }
  stop() {
    if (this.recognizer) {
      this.recognizer.dispose();
    }
  }
}
